importJar("org.slf4j:slf4j-api:jar:1.7.21");
importJar("org.slf4j:slf4j-simple:jar:1.7.21");
importJar("com.google.code.gson:gson:jar:2.8.2");

importJar("mysql:mysql-connector-java:jar:5.1.47");
importJar("commons-dbutils:commons-dbutils:jar:1.7");

// 加载数据库访问类.
importClass("com.lamb.script.core.utils.MySqlShardDataSource");
importClass("org.apache.commons.dbutils.QueryRunner");
importClass("org.apache.commons.dbutils.handlers.MapListHandler");

importClass("java.util.zip.CRC32");
importClass("java.lang.String");

var jdbcProperties = importProperties("classpath:/script.jdbc.properties");
var dataSource = new MySqlShardDataSource(jdbcProperties);

var oneDayMs = 86400000;

// 转为二位数的字符串.
function to2Num(number) {
    return number >= 10 ? "" + number : "0" + number;
}

// 格式化时间.
function formatDateTime(date) {
    var dateStr = date.getFullYear() + "-" + to2Num(date.getMonth() + 1) + "-" + to2Num(date.getDate());
    var timeStr = to2Num(date.getHours()) + ":" + to2Num(date.getMinutes()) + ":" + to2Num(date.getSeconds())
    return dateStr + " " + timeStr;
}

// 处理当前时间.
var now = new Date();
// 东八区 减去8小时（28800000）,
var startTimeOfDay = new Date(now.getTime() - (now.getTime() % oneDayMs) - 28800000);
var todayDT = formatDateTime(startTimeOfDay);
var nextDayDT = formatDateTime(new Date(startTimeOfDay.getTime() + oneDayMs));

// crc32 后再分20表.
function mod3220Fun (corpId){
    var crc32 = new CRC32();
    crc32.update(JavaString.valueOf(corpId).getBytes());
    var mod = crc32.getValue() % 20;
    return to2Num(mod);
}

// sql 脚本执行器.
function mysql_query(env, sql) {
    var queryRunner = new QueryRunner();
    var connection = dataSource.getConnection(env);
    var mysql_query_params = util.newArray(arguments.length - 2);
    for (var mysql_query_i = 2; mysql_query_i < arguments.length; mysql_query_i++) {
        mysql_query_params[mysql_query_i - 2] = arguments[mysql_query_i];
    }
    return queryRunner.query(connection, sql, new MapListHandler(), mysql_query_params);
}

// mysql 更新
function mysql_update(env, sql) {
    var queryRunner = new QueryRunner();
    var connection = dataSource.getConnection(env);
    var mysql_update_params = util.newArray(arguments.length - 2);
    for (var mysql_update_i = 2; mysql_update_i < arguments.length; mysql_update_i ++) {
        mysql_update_params[mysql_update_i - 2] = arguments[mysql_update_i];
    }
    return queryRunner.update(connection, sql, mysql_update_params);
}